from bs4 import BeautifulSoup
from urllib import parse
import re
import math
import random
import requests

"""番号页面解析"""
class FanHaoPageParser(object):

	"""获取番号页面的信息"""
	def get_page_info(self, response_text):
		if response_text is None:
			return None
		soup = BeautifulSoup(response_text, 'lxml')
		base_info = self.get_fanhao_baseinfo(soup)
		magnet_info, url = self.get_magnet_info(soup)
		img_info = self.get_fanhao_imgs(soup)
		return base_info, magnet_info, img_info, url

	"""获取番号的基础信息"""
	def get_fanhao_baseinfo(self, soup):
		if soup is None:
			return None
		info = {}
		try:
			title_node = soup.find('div', class_='container').find('h3')
			info['title'] = title_node.get_text()
			img_node = soup.find('a', class_='bigImage').find('img')
			info['img'] = img_node['src']

			info_node = soup.find('div', class_='col-md-3 info')
			fanhao_node = info_node.find('span', text=re.compile(r"識別碼:")).find_next('span')
			info['fanhao'] = fanhao_node.get_text().strip()
			info['date'] = info_node.find('span', text=re.compile(r"發行日期:")).next_sibling.strip()
			# print(info['date'])
			info['changdu'] = info_node.find('span', text=re.compile(r"長度:")).next_sibling.strip()
			# print(info['changdu'])
			info['zhizuoshang'] = info_node.find('span', text=re.compile(r"製作商:")).find_next('a').get_text().strip()
			# print(info['zhizuoshang'])
			info['faxingshang'] = info_node.find('span', text=re.compile(r"發行商:")).find_next('a').get_text().strip()
			# print(info['faxingshang'])
			leibie_nodes = info_node.find('p', text=re.compile(r"類別:")).find_next('p').find_all('span')
			# print(leibie_nodes)
			leibies = []
			for leibie_node in leibie_nodes:
				leibies.append(leibie_node.find('a').get_text().strip())
			info['leibies'] = leibies

			yanyuan_nodes = info_node.find('p', class_='star-show').find_next('p').find_all('span')
			yanyuans = []
			for yanyuan_node in yanyuan_nodes:
				yanyuans.append(yanyuan_node.find('a').get_text().strip())
			info['yanyuans'] = yanyuans
			# print(info)
		except Exception as e:
			print("craw faile:%s"%(e))

		return info


	"""获取磁力链接的信息"""
	def get_magnet_info(self, soup):
		if soup is None:
			return None
		magnets = []
		try:
			args_text = soup.find('script', text=re.compile(r"gid")).get_text()
			temp_args = args_text.split(';')
			gid = temp_args[0].split('=')[1].strip()
			uc = temp_args[1].split('=')[1].strip()
			img = temp_args[2].split('=')[1].strip()
			floor = math.floor(random.random() * 1000 + 1)

			url = "https://www.busdmm.us/ajax/uncledatoolsbyajax.php?gid=" + gid + "&lang=zh&img=" + img + "&uc=" + uc + "&floor=" + str(floor)

			# print(gid, uc, img, floor)

			print("magnet-url:{}".format(url))

			headers = {
				'X-Requested-With': 'XMLHttpRequest',
				'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
		              '(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
				'Referer': 'https://www.busdmm.us'
			}

			respnese = requests.get(url,  headers = headers, timeout = 10)
			# print(respnese.text)
			magnet_soup = BeautifulSoup(respnese.text, 'lxml')
			magnet_nodes = magnet_soup.find_all('tr')
			# print(magnet_nodes)
			for magnet_node in magnet_nodes:
				magnet_info = {}
				info_nodes = magnet_node.find_all('td')
				magnet_info['link'] = info_nodes[0].find('a')['href']
				magnet_info['link_title'] = info_nodes[0].find('a').get_text().strip()
				magnet_info['size'] = info_nodes[1].find('a').get_text().strip()
				magnets.append(magnet_info)

			# print(magnets)
		except Exception as e:
			print(e)

		return magnets, url


	"""获取番号的样图"""
	def get_fanhao_imgs(self, soup):
		if soup is None:
			return None

		imgs = []
		try:
			img_nodes = soup.find('div', id='sample-waterfall').find_all('div', class_='photo-frame')
			for node in img_nodes:
				img_src = node.find('img')['src']
				imgs.append(img_src)
		except Exception as e:
			print(e)
		return imgs


	
